<?php

namespace Kangcg\Application\Validate\Rules;

use Kangcg\Application\Validate\Exception\RuleConfigureException;
use Kangcg\Application\Validate\Validator;
use Kangcg\Helper\Validate\Base;

class IfRequired implements RuleInterface
{
    use RuleTrait;

    public $field;

    protected function beforeRun(&$value) : bool{
        return true;
    }

    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        if($value === null || $value === ''){
            $validator->setError($this->getMessage($field));
            return false;
        }
    }

    public function extra($extra)
    {
        if(isset($extra['field'])){
           return $extra;
        }

        if(is_string($extra)){
            return [
                'field' => $extra,
            ];
        }

        throw new RuleConfigureException("验证规则 IfRequired 配置错误，期望【 if_required => '数据字段名' | if_required => [ if_required => 数据字段名'] 】!");
    }
}
